/* 点击按钮存在异步操作时，让按钮处于加载状态
-------------------------- */
const btnLoadingMixin = {
  data () {
    return {
      loadingBtn: '', // 加载按钮的名称，用于区别同一组件不同的按钮
      loadingRow: null // 针对表格不同行的按钮
    }
  },
  methods: {
    /**
     * 按钮的异步操作封装器
     * @param {string} btnName 加载按钮的名称，用于区别同一组件不同的按钮
     * @param {string} rowIndex 当前按钮对应表格所在下标，从0开始
     * @param {function} asyncCb 按钮异步操作
     * @desc rowIndex选填
     */
    async AsyncLoading (btnName, rowIndex, asyncCb) {
      let Index = rowIndex
      let AsyncCb = asyncCb
      if (typeof rowIndex !== 'number') {
        AsyncCb = rowIndex
        Index = null
      }
      if (typeof Index === 'number') this.loadingRow = Index
      this.loadingBtn = btnName
      try {
        await AsyncCb()
        this.loadingBtnEnd()
      } catch (e) {
        this.loadingBtnEnd()
      }
    },
    /* 加载结束
    -------------------------- */
    loadingBtnEnd () {
      this.loadingBtn = ''
      this.loadingRow = null
    }
  }
}

export default btnLoadingMixin
